package com.lrm.service;

import com.lrm.dao.UserRepository;
import com.lrm.po.User;
import com.lrm.util.MD5Utils;
import com.lrm.util.MyBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.Temporal;
import org.springframework.data.jpa.repository.query.Jpa21Utils;
import org.springframework.stereotype.Service;

import javax.persistence.TemporalType;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User checkUser(String username, String password) {
        User user = userRepository.findByUsernameAndPassword(username, MD5Utils.code(password));
        return user;
    }



    @Override
    public List<User> findByName(String username) {
        return userRepository.findUserByUsername(username);
    }

    public void update(User user){

        System.out.println("userName = "+user.getUsername());
        Optional<User> selectData = userRepository.findById(user.getId());//selectData包括session里的user所有信息，包括不可修改的属性
            user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            BeanUtils.copyProperties(user,selectData.get(),MyBeanUtils.getNullPropertyNames(user));
            userRepository.save(selectData.get());
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

    @Override
    public void save(User user) {
        System.out.println("save user:userName = "+user.getUsername());
            user.setCreateTime(new Timestamp(System.currentTimeMillis()));
            user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            if(user.getAvatar() == null){
                user.setAvatar("https://img1.imgtp.com/2023/08/15/lSVYdXx3.jpg");
            }
            user.setType(2);
            userRepository.save(user);
        }
}
